package com.workstudy.wstudy.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.workstudy.common.constant.UserConstants;
import com.workstudy.common.core.domain.entity.SysRole;
import com.workstudy.common.core.domain.entity.SysUser;
import com.workstudy.common.utils.ShiroUtils;
import com.workstudy.common.utils.StringUtils;
import com.workstudy.common.utils.file.FileUtils;
import com.workstudy.system.domain.SysUserRole;
import com.workstudy.system.mapper.SysUserRoleMapper;
import com.workstudy.system.service.ISysPostService;
import com.workstudy.system.service.ISysRoleService;
import com.workstudy.system.service.ISysUserService;
import com.workstudy.wstudy.domain.UploadStudent;
import com.workstudy.wstudy.domain.WstCredit;
import com.workstudy.wstudy.domain.WstPostUser;
import com.workstudy.wstudy.service.IWstCreditService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.workstudy.common.annotation.Log;
import com.workstudy.common.enums.BusinessType;
import com.workstudy.wstudy.domain.WstStudent;
import com.workstudy.wstudy.service.IWstStudentService;
import com.workstudy.common.core.controller.BaseController;
import com.workstudy.common.core.domain.AjaxResult;
import com.workstudy.common.utils.poi.ExcelUtil;
import com.workstudy.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 学生Controller
 * 
 * @author sun
 * @date 2021-04-04
 */
@Controller
@RequestMapping("/wstudy/student")
public class WstStudentController extends BaseController
{
    private String prefix = "wstudy/student";

    @Autowired
    private Environment env;

    @Autowired
    private IWstStudentService wstStudentService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private IWstCreditService creditService;

    @RequiresPermissions("wstudy:student:view")
    @GetMapping()
    public String student()
    {
        return prefix + "/student";
    }
    @GetMapping("/importStudent")
    public String importStudent()
    {
        return prefix + "/importStudent";
    }
    /**
     * 查询学生列表
     */
    @RequiresPermissions("wstudy:student:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WstStudent wstStudent)
    {
        startPage();
        List<WstStudent> list = wstStudentService.selectWstStudentList(wstStudent);
        return getDataTable(list);
    }

    /**
     * 导出学生列表
     */
    @RequiresPermissions("wstudy:student:export")
    @Log(title = "学生", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WstStudent wstStudent)
    {
        List<WstStudent> list = wstStudentService.selectWstStudentList(wstStudent);
        ExcelUtil<WstStudent> util = new ExcelUtil<WstStudent>(WstStudent.class);
        return util.exportExcel(list, "student");
    }

    /**
     * 新增学生
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("roles", roleService.selectRoleAll().stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostAll());
        return prefix + "/add";
    }

    @GetMapping("/postStuPage/{postId}")
    public String postStuPage(@PathVariable("postId")Long postId, ModelMap map)
    {
        map.put("postId",postId);
        return prefix + "/post_student";
    }

    @GetMapping("/studentPost")
    public String studentPost()
    {
        return prefix + "/student_post";
    }

    /**
     * 查询学生列表
     */
    @PostMapping("/list/{postId}/{userId}/{status}")
    @ResponseBody
    public TableDataInfo listStu(WstStudent wstStudent,@PathVariable("postId")Long postId,@PathVariable("userId")Long userId,@PathVariable("status")String status)
    {
        startPage();
        WstPostUser postUser = new WstPostUser();
        if (userId!=0){
            postUser.setUserId(userId);
        }
        if (postId!=0){
            postUser.setPostId(postId);
        }
        postUser.setStatus(status);
        List<WstStudent> list = wstStudentService.selectPostStuList(postUser,wstStudent);
        return getDataTable(list);
    }

    /**
     * 查询学生列表
     */
    @PostMapping("/list/post")
    @ResponseBody
    public TableDataInfo list()
    {
        startPage();
        WstPostUser postUser = new WstPostUser();
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        postUser.setUserId(user.getUserId());
        List<WstPostUser> list = wstStudentService.selectStuPostList(postUser);
        return getDataTable(list);
    }

    /**
     * 新增保存学生
     */
    @RequiresPermissions("wstudy:student:add")
    @Log(title = "学生", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WstStudent wstStudent)
    {
        SysUser user = wstStudent;
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName())))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        return toAjax(wstStudentService.insertWstStudent(wstStudent));
    }

    /**
     * 修改学生
     */
    @GetMapping("/edit/{studentId}")
    public String edit(@PathVariable("studentId") Long studentId, ModelMap mmap)
    {
        Long userId = studentId;
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        WstStudent wstStudent = wstStudentService.selectWstStudentById(studentId);
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        mmap.put("wstStudent", wstStudent);
        return prefix + "/edit";
    }

    /**
     * 完善学生信息
     */
    @GetMapping("/info")
    public String info(ModelMap mmap)
    {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Long userId = user.getUserId();
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        WstStudent wstStudent = wstStudentService.selectWstStudentById(userId);
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        mmap.put("wstStudent", wstStudent);
        return prefix + "/info";
    }

    /**
     * 学生详情
     */
    @GetMapping("/details/{studentId}")
    public String details(@PathVariable("studentId") Long studentId, ModelMap mmap)
    {
        Long userId = studentId;
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        WstStudent wstStudent = wstStudentService.selectWstStudentById(studentId);
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        mmap.put("wstStudent", wstStudent);
        return prefix + "/details";
    }

    /**
     * 学生详情
     */
    @PostMapping("/query")
    @ResponseBody
    public AjaxResult query(Long studentId)
    {
        Long userId = studentId;
        SysUser user =(SysUser) SecurityUtils.getSubject().getPrincipal();
        if (user.getRoles().size()==0 || user.getRoles().get(0).getRoleKey().equals("student")){
            WstStudent wstStudent = wstStudentService.selectWstStudentById(studentId==null?user.getUserId():studentId);
            return AjaxResult.success(wstStudent.getPoor()==null?"yes":"no",wstStudent);
        }
        return AjaxResult.success("other");
    }

    /**
     * 修改保存学生
     */
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WstStudent wstStudent)
    {
        SysUser user = wstStudent;
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(wstStudentService.updateWstStudent(wstStudent));
    }

    @GetMapping("/downloadTemplate")
    public void resourceDownload(String resource, String downloadName, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        // 本地资源路径
        String localPath = env.getProperty("ruoyi.profile");
        // 数据库资源地址
        String downloadPath = localPath + resource;
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }

    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport,HttpServletRequest request,HttpServletResponse response) throws Exception
    {
        ExcelUtil<UploadStudent> util = new ExcelUtil<UploadStudent>(UploadStudent.class);
        WstCredit credit = creditService.selectWstCreditById(new Long(1));
        List<UploadStudent> userList = util.importExcel(file.getInputStream());
        List<SysUser> users = new ArrayList<>();
        List<WstStudent> students = new ArrayList<>();
        List<SysUserRole> userRoles = new ArrayList<>();
        String operName = ShiroUtils.getSysUser().getLoginName();
        for (UploadStudent s:userList){
            SysUser u = new SysUser();
            u.setLoginName(s.getStudentId());
            u.setUserName(s.getStudentName());
            u.setPhonenumber(s.getPhone());
            u.setDeptId(s.getDeptId());
            users.add(u);
        }
        String message = userService.importUser(users, updateSupport, operName);
        int row = 0;
        for (UploadStudent s:userList){
            WstStudent wstStudent = new WstStudent();
            SysUserRole userRole = new SysUserRole();
            SysUser user = userService.selectUserByLoginName(s.getStudentId());
            wstStudent.setStudentId(user.getUserId());
            wstStudent.setIdentity(s.getIdentity());
            wstStudent.setGrade(s.getGrade());
            wstStudent.setBankCard(s.getKa());
            wstStudent.setCredit(credit.getDescore());
            userRole.setUserId(user.getUserId());
            //固定学生的角色
            userRole.setRoleId(new Long(100));
            students.add(wstStudent);
            userRoles.add(userRole);
        }
        wstStudentService.insertWstStudentList(students );
        userRoleMapper.batchUserRole(userRoles);
        return AjaxResult.success(message);
    }

    /**
     * 删除学生
     */
    @RequiresPermissions("wstudy:student:remove")
    @Log(title = "学生", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(wstStudentService.deleteWstStudentByIds(ids));
    }
}